﻿using SXICE.Core;
using SXICE.Core.Domains;
using SXICE.Core.Helpers;
using SXICE.Core.Infrastructure;
using SXICE.Core.Models;
using SXICE.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SXICE.Repository
{
    /// <summary>
    /// 权限仓储
    /// </summary>
    public class RightsRepository : DBContext, IRightsRepository
    {
        private readonly ILog log;
        private readonly ICacheBase cacheBase;

        public RightsRepository(ILog log, ILocalCache localCache)
        {
            this.log = log;
            this.cacheBase = localCache;
        }

        public List<Menu> Menus
        {
            get
            {
                try
                {
                    return this.cacheBase.GetOrAdd("Menu_Cache", () => MenuDB.AsQueryable().OrderBy(c => c.Order).ToList());
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                    return new List<Menu>();
                }
            }
        }

        public ReturnResult AddRights(int roleId, List<int> menuIds)
        {
            try
            {
                RightsDB.AsDeleteable().Where(c => c.RoleId == roleId).AddQueue();
                RightsDB.AsInsertable(menuIds.Select(c => new Rights { MenuId = c, RoleId = roleId }).ToList()).AddQueue();
                RightsDB.Context.SaveQueues();
                return ReturnResult.GetResult();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }

        public ReturnResult AddRole(string name)
        {
            try
            {
                return RolesDB.Insert(new Roles { Name = name }) ? true.ToResult() : RepositoryErrors.ROLE_ADD_FAILED.ToResult("角色添加失败");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }

        public ReturnResult DeleteRole(int id)
        {
            try
            {
                return RolesDB.DeleteById(id) ? true.ToResult() : RepositoryErrors.ROLE_DELETE_FAILED.ToResult("角色删除失败");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }

        public ReturnResult<List<Rights>> GetRights(int roleId)
        {
            try
            {
                return RightsDB.GetList(c => c.RoleId == roleId).ToResult();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult<List<Rights>>();
            }
        }

        public ReturnResult<Roles> GetRoleById(int roleId)
        {
            try
            {
                var role = RolesDB.GetById(roleId);
                if (null == role)
                    return RepositoryErrors.ROLE_IS_NOT_EXISTED.ToResult<Roles>("角色不存在");
                return role.ToResult();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult<Roles>();
            }
        }

        public ReturnResult<List<Roles>> GetRoles()
        {
            try
            {
                return RolesDB.GetList().ToResult();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult<List<Roles>>();
            }
        }

        public ReturnResult HasRights(int roleId, string code)
        {
            try
            {
                var menu = Menus.Find(c => c.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase));
                if (null == menu)
                    return RepositoryErrors.NO_RIGHTS.ToResult("没有此菜单，请勿非法访问");
                return RightsDB.IsAny(c => c.MenuId == menu.Id && c.RoleId == roleId) ? true.ToResult() : RepositoryErrors.NO_RIGHTS.ToResult("您无权限访问" + menu.Name);
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }

        public ReturnResult RoleExists(string name)
        {
            try
            {
                return RolesDB.IsAny(c => c.Name == name) ? true.ToResult() : RepositoryErrors.ROLE_IS_EXISTED.ToResult("此角色名称不已存在");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }

        public ReturnResult RoleExists(int roleId)
        {
            try
            {
                return RolesDB.IsAny(c => c.Id == roleId) ? true.ToResult() : RepositoryErrors.ROLE_IS_EXISTED.ToResult("此角色已不存在");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }

        public ReturnResult UpdateRole(Roles roles)
        {
            try
            {
                DoctorDB.AsSugarClient().Updateable<Doctor>().SetColumns(c => c.RoleName == roles.Name).Where(c => c.RoleId == roles.Id).AddQueue();
                RolesDB.AsUpdateable(roles).AddQueue();
                var result = RolesDB.Context.SaveQueues();
                return result > 0 ? true.ToResult() : RepositoryErrors.ROLE_UPDATE_FAILED.ToResult("角色修改失败");
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return ex.ToExceptionResult();
            }
        }
    }
}
